<?php

namespace seecms\controller;

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeEnlarge;
use Endroid\QrCode\Writer\PngWriter;
use seecms\lib\provider\UserLogin;
use seecms\See;
use seecms\lib\Auth;
use seecms\lib\Captcha;
use seecms\SeeLang;
use seecms\lib\response\HtmlResponse;
use seecms\lib\response\JsonResponse;
use seecms\lib\response\RedirectResponse;

class User
{

    protected function init(): array
    {
        $type = See::request()->get('type') ?: 1;

        $setting = See::provider()->general->login;

        $data['support'] = json_decode($setting['support'] ?? '') ?: [];
        $data['sms_code_len'] = $setting['sms_code_len'] ?? 4;
        $keep_login_data = See::provider()->user_login->keepLoginData();
        $data['keep'] = $keep_login_data;
        $data['type'] = $type;
        $data['type_file'] = 'user/type_' . $type . '.twig';

        // 获取支持登录的方式
        $data['support_login_method'] = See::provider()->user_login->support();

        return $data;
    }

    /**
     * @return string
     */
    public function login(): string
    {
        $data = $this->init();

        return See::view()->fetch('user/login', $data);
    }

    /**
     * @return HtmlResponse
     */
    public function captcha(): HtmlResponse
    {
        $captcha = new Captcha();

        return $captcha->output();
    }

    /**
     * app 扫码登录
     * @return HtmlResponse
     * @throws \Exception
     */
    public function appScan(): HtmlResponse
    {
        $token = See::provider()->user_login->appScan();

        $writer = new PngWriter();
        $qrCode = QrCode::create($token)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
            ->setSize(230)
            ->setRoundBlockSizeMode(new RoundBlockSizeModeEnlarge())
            ->setForegroundColor(new Color(0, 0, 0))
            ->setBackgroundColor(new Color(255, 255, 255));
        $result = $writer->write($qrCode);
        header('Content-Type: ' . $result->getMimeType());
        return new HtmlResponse($result->getString());
    }

    /**
     * 用户登录
     * @return JsonResponse
     */
    public function doLogin(): JsonResponse
    {
        $user_login = See::provider()->user_login;
        $data = See::request()->post();

        if (empty($data['type'] ?? '')) {
            $data['type'] = UserLogin::TYPE_ACCOUNT;
        }

        if (in_array($data['type'], [1, 2])) {
            $user_login->keepLogin($data);
        }

        if ($data['type'] == UserLogin::TYPE_ACCOUNT && !See::config()->debug()) {
            $captcha = new Captcha();
            $verify = $captcha->check($data['verify'] ?? '');
            if ($verify === false) {
                return JsonResponse::error(SeeLang::login('verify_code_error'));
            }
        }

        $result = $user_login->doLogin($data);

        return JsonResponse::result($result);
    }


    /**
     * 登出页面
     * @return RedirectResponse
     */
    public function logout(): RedirectResponse
    {
        See::provider()->user_login->logout();

        return new RedirectResponse(auth_route('login'));
    }

    /**
     * 没有访问权限页面
     * @return string
     */
    public function noPermission(): string
    {
        $url = See::request()->param('url');

        $record = See::table()->user_rule->where('url', $url)->find();

        return See::view()->fetch('user/no.permission', [
            'title' => $record ? ($record['title'] ?? '') : '',
            'url' => $url,
            'is_dialog' => true
        ]);
    }
}